package com.love.marriage.defaultAmountConfig.service.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.love.marriage.common.enums.DefaultAmountTypeEnum;
import com.love.marriage.common.vo.SecurityUser;
import com.love.marriage.defaultAmountConfig.entity.DefaultAmountConfig;
import com.love.marriage.defaultAmountConfig.mapper.DefaultAmountConfigMapper;
import com.love.marriage.defaultAmountConfig.service.DefaultAmountConfigService;
import com.love.marriage.defaultAmountConfig.vo.DefaultAmountConfigVo;
import com.love.marriage.defaultAmountConfigRecord.service.DefaultAmountConfigRecordService;
import com.love.marriage.userCallRetrieval.service.UserCallRetrievalService;
import com.love.marriage.userCallRetrieval.vo.UserCallRetrievalVo;
import com.love.marriage.userChatInfo.service.UserChatInfoService;
import com.love.marriage.userChatInfo.vo.UserChatInfoVo;
import com.love.marriage.utils.StringUtils;
import com.love.marriage.utils.UserUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.List;
import java.util.concurrent.CompletableFuture;

/**
 * <p>
 * description:  默认金额配置表服务实现类
 * author:       mybatisPlus
 * createDate:   2024-10-25 07:42:11
 * version:      1.0.0
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class DefaultAmountConfigServiceImp extends ServiceImpl<DefaultAmountConfigMapper, DefaultAmountConfig> implements DefaultAmountConfigService {

    private final DefaultAmountConfigMapper defaultAmountConfigMapper;

    private final DefaultAmountConfigRecordService defaultAmountConfigRecordService;

    private final UserCallRetrievalService userCallRetrievalService;

    private final UserChatInfoService userChatInfoService;

    @Override
    public Page<DefaultAmountConfigVo> getPage(Long pageNum, Long pageSize, DefaultAmountConfigVo defaultAmountConfigVo) {
        Page<DefaultAmountConfigVo> page = new Page<>(pageNum == null ? 1 : pageNum, pageSize == null ? 10 : pageSize);
        return defaultAmountConfigMapper.getPage(page, defaultAmountConfigVo);
    }

    @Override
    public DefaultAmountConfigVo queryDefaultAmountConfig(Long id) {
        return defaultAmountConfigMapper.queryDefaultAmountConfig(id);
    }

    @Override
    public DefaultAmountConfigVo queryDefaultAmountConfigByCode(String code) {
        if ("getPhone".equals(code)) {
            // 查询用户获取手机号次数
            SecurityUser loginUser = UserUtils.getLoginUser();
            if (loginUser != null) {
                UserCallRetrievalVo userCallRetrievalVo = userCallRetrievalService.queryUserCallRetrievalByUerId(loginUser.getId());
                int time = ((userCallRetrievalVo == null ? 0 : userCallRetrievalVo.getRetrievalCount()) + 1) % 4;
                DefaultAmountConfigVo defaultAmountConfigVo = defaultAmountConfigMapper.queryDefaultAmountConfigByCode(code + time);
                UserChatInfoVo userChatInfoVo = userChatInfoService.queryUserChatInfoByUserId(loginUser.getId(), DefaultAmountTypeEnum.GET_PHONE_NUM.getCode());
                if (userChatInfoVo != null && userChatInfoVo.getChatCount() > 0) {
                    defaultAmountConfigVo.setFreeCharge(true);
                    // 更新免费查询电话号码次数
                    userChatInfoVo.setChatCount(userChatInfoVo.getChatCount() - 1);
                    userChatInfoService.updateUserChatInfo(userChatInfoVo);
                } else {
                    defaultAmountConfigVo.setFreeCharge(false);
                }
                return defaultAmountConfigVo;
            }
        }
        return defaultAmountConfigMapper.queryDefaultAmountConfigByCode(code);
    }

    @Override
    public List<DefaultAmountConfigVo> queryDefaultAmountConfigByCodes(List<String> codes) {
        return defaultAmountConfigMapper.queryDefaultAmountConfigByCodes(codes);
    }

    @Override
    public DefaultAmountConfigVo addDefaultAmountConfig(DefaultAmountConfigVo defaultAmountConfigVo) {
        DefaultAmountConfigVo db = queryDefaultAmountConfigByCode(defaultAmountConfigVo.getConfigCode());
        if(db != null) {
            throw new RuntimeException("配置编码已存在");
        }
        DefaultAmountConfig defaultAmountConfig = new DefaultAmountConfig();
        BeanUtils.copyProperties(defaultAmountConfigVo, defaultAmountConfig);
        defaultAmountConfigMapper.insert(defaultAmountConfig);
        DefaultAmountConfigVo res = new DefaultAmountConfigVo();
        BeanUtils.copyProperties(defaultAmountConfig, res);
        
        // 异步记录新增操作
        asyncRecordInsertOperation(res, "新增默认金额配置");
        
        return res;
    }

    @Override
    public DefaultAmountConfigVo updateDefaultAmountConfig(DefaultAmountConfigVo defaultAmountConfigVo) {
        // 获取修改前的数据
        DefaultAmountConfigVo oldConfig = queryDefaultAmountConfig(defaultAmountConfigVo.getId());
        
        DefaultAmountConfig defaultAmountConfig = new DefaultAmountConfig();
        BeanUtils.copyProperties(defaultAmountConfigVo, defaultAmountConfig);
        defaultAmountConfigMapper.updateById(defaultAmountConfig);
        
        // 异步记录修改操作
        if (oldConfig != null) {
            asyncRecordUpdateOperation(oldConfig, defaultAmountConfigVo, "修改默认金额配置");
        }
        
        return defaultAmountConfigVo;
    }

    @Override
    public Boolean deleteDefaultAmountConfig(String ids) {
        if(StringUtils.isEmpty(ids)) {
            return true;
        }
        List<String> idArr = Arrays.asList(ids.split(","));
        
        // 异步记录删除操作
        for (String id : idArr) {
            DefaultAmountConfigVo oldConfig = queryDefaultAmountConfig(Long.valueOf(id));
            if (oldConfig != null) {
                asyncRecordDeleteOperation(oldConfig, "删除默认金额配置");
            }
        }
        
        defaultAmountConfigMapper.deleteBatchIds(idArr);
        return true;
    }

    /**
     * 异步记录新增操作
     */
    @Async
    public CompletableFuture<Void> asyncRecordInsertOperation(DefaultAmountConfigVo newConfig, String operationReason) {
        try {
            defaultAmountConfigRecordService.recordInsertOperation(newConfig, operationReason);
            log.info("异步记录新增操作成功, configId: {}, configCode: {}", newConfig.getId(), newConfig.getConfigCode());
        } catch (Exception e) {
            log.error("异步记录新增操作失败, configId: {}, configCode: {}", newConfig.getId(), newConfig.getConfigCode(), e);
        }
        return CompletableFuture.completedFuture(null);
    }

    /**
     * 异步记录修改操作
     */
    @Async
    public CompletableFuture<Void> asyncRecordUpdateOperation(DefaultAmountConfigVo oldConfig, DefaultAmountConfigVo newConfig, String operationReason) {
        try {
            defaultAmountConfigRecordService.recordUpdateOperation(oldConfig, newConfig, operationReason);
            log.info("异步记录修改操作成功, configId: {}, configCode: {}", newConfig.getId(), newConfig.getConfigCode());
        } catch (Exception e) {
            log.error("异步记录修改操作失败, configId: {}, configCode: {}", newConfig.getId(), newConfig.getConfigCode(), e);
        }
        return CompletableFuture.completedFuture(null);
    }

    /**
     * 异步记录删除操作
     */
    @Async
    public CompletableFuture<Void> asyncRecordDeleteOperation(DefaultAmountConfigVo oldConfig, String operationReason) {
        try {
            defaultAmountConfigRecordService.recordDeleteOperation(oldConfig, operationReason);
            log.info("异步记录删除操作成功, configId: {}, configCode: {}", oldConfig.getId(), oldConfig.getConfigCode());
        } catch (Exception e) {
            log.error("异步记录删除操作失败, configId: {}, configCode: {}", oldConfig.getId(), oldConfig.getConfigCode(), e);
        }
        return CompletableFuture.completedFuture(null);
    }
}
